import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('表单加校验'),
        ),
        body: const MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _unameCtl = TextEditingController();
  TextEditingController _upwdCtl = TextEditingController();
  GlobalKey _gk = GlobalKey<FormState>();

  var reg_uname = RegExp(r"^\w{1,10}$");
  var reg_upwd = RegExp(r"^\d{6}$");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _gk,
        // autovalidateMode: AutovalidateMode.always,
        child: Column(children: <Widget>[
          TextFormField(
            autofocus: true,
            controller: _unameCtl,
            decoration: const InputDecoration(
              labelText: "用户名",
              hintText: "必填，10个字符以内，字母或数字的组合",
              icon: Icon(Icons.person),
            ),
            validator: (v) {
              return reg_uname.hasMatch(v!) ? null : "用户名长度超出10个字符";
            },
          ),
          TextFormField(
            controller: _upwdCtl,
            decoration: const InputDecoration(
              labelText: "密码",
              hintText: "6位数字",
              icon: Icon(Icons.lock),
            ),
            obscureText: true,
            validator: (v) {
              return reg_upwd.hasMatch(v!) ? null : "最小6位密码";
            },
          ),
          ElevatedButton(onPressed: () {
            if((_gk.currentState as FormState).validate()) {
              print("用户名：${_unameCtl.text.trim()},密码：${_upwdCtl.text.trim()}");
            }
          }, child: const Text("登录"))
        ]),
      ),
    );
  }
}
